//
//  OauthViewController.swift
//  bboySinaWeibo
//
//  Created by apple on 15/11/17.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthViewController: UIViewController {

    let client_id = "1831572088"
    
    let redirect_uri = "http://www.baidu.com"
    
    //定义一个网页属性
    let webView = UIWebView()
    
    //MARK 监听方法
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount() {
        let jsString = "document.getElementById('userId').value = '15247191827' , document.getElementById('passwd').value = '910802bboygang';"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    

    //苹果专为手码创建空间设置的 实现了这个方法 就不会走SB 或者SIB
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUPUI()
        
        //加载网页
        loadOauthPage()
        
    }

  
    //加载网页 
 
    func loadOauthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
    }
    private func setUPUI() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")

    }
}

//webView 的协议方法
extension OauthViewController:UIWebViewDelegate {
    
    /*
    Optional(https://api.weibo.com/oauth2/authorize?client_id=1831572088&redirect_uri=http://www.baidu.com)
    Optional(https://api.weibo.com/oauth2/authorize)
    Optional(http://www.baidu.com/?code=7c32118b080f84c3475978065ef300b9)
    Optional(https://m.baidu.com/?code=7c32118b080f84c3475978065ef300b9&from=844b&vit=fps)

    */
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL)
        return true
    }
    
}